package com.spring.format.code.generation.util.file;

import java.util.Date;
import java.util.List;

import com.spring.format.code.generation.constants.Constants;
import com.spring.format.code.generation.constants.FileNameEnumType;
import com.spring.format.code.generation.mybatis.po.TablePO;
import com.spring.format.code.generation.mybatis.vo.CreateFileVO;
import com.spring.format.code.generation.mybatis.vo.JavaAttributeVO;
import com.spring.format.code.generation.util.CommonCodeUtil;
import com.spring.format.code.generation.util.FieldUtil;
import com.spring.format.code.generation.util.NameUtil;
import com.spring.format.code.generation.util.PathUtil;

/**
 * 文件生成帮助类
 * 
 * @author lenovo
 *
 */
public class CommonServiceFileUtil {
	private CommonServiceFileUtil() {
	}

	public static String content(CreateFileVO fileVO) {
		TablePO tablePO = fileVO.getTablePO();
		List<JavaAttributeVO> attrVOList = fileVO.getAttrVOList();
		// po的类名
		String poName = NameUtil.createFileName(tablePO.getTable_name(), FileNameEnumType.PO_NAME);
		// vo的类名
		String voName = NameUtil.createFileName(tablePO.getTable_name(), FileNameEnumType.VO_NAME);
		// form的类名
		String formName = NameUtil.createFileName(tablePO.getTable_name(), FileNameEnumType.FORM_NAME);
		// dao api名称
		String daoApiName = NameUtil.createFileName(tablePO.getTable_name(), FileNameEnumType.DAO_API_NAME);
		// dao impl 名称
		String daoImplName = NameUtil.createPrivateName(tablePO.getTable_name(), FileNameEnumType.DAO_API_NAME);
		StringBuilder attribute = new StringBuilder();
		/** 头部 **/
		attribute.append(head(tablePO, daoImplName, daoApiName));
		/** 新增 **/
		attribute.append(add(formName, poName, daoImplName));
		/** 批量新增 **/
		attribute.append(addBatch(formName, poName, daoImplName));
		/** 删除 **/
		attribute.append(deleteById(poName, daoImplName));
		/** 修改 **/
		attribute.append(update(formName, poName, daoImplName));
		/** 根据id查询 **/
		attribute.append(queryById(voName, poName, daoImplName));
		/** 分页 **/
		attribute.append(page(formName,voName, poName, daoImplName));
		/** 获取数据集合 **/
		attribute.append(list(formName,voName, poName, daoImplName));
		/** 批量修改状态 **/
		//attribute.append(editStatusBatch(poName, daoImplName));
		/** 修改数据状态 **/
		attribute.append(editStatus(poName, daoImplName));
		/** createVO **/
		attribute.append(createVO(voName, poName));
		/** poList 2 voList **/
		attribute.append(createVOList(voName, poName));
		/** voList 2 poList **/
		attribute.append(createPOList(formName, poName));
		/** 添加验证 **/
		attribute.append(addValidate(formName, poName, daoImplName));
		/** 编辑验证 **/
		attribute.append(updateValidate(formName, poName, daoImplName));
		/** 特殊字段，特殊方法的追加代码(如排序字段，唯一索引字段，有自己方法的字段) **/
		for (JavaAttributeVO attriVO : attrVOList) {
			attribute.append(specialFieldAddition(attriVO, formName, poName, daoImplName));
		}
		/** 文件结束 **/
		attribute.append(CommonCodeUtil.methodEnd("} //end class"));
		return attribute.toString();

	}

	/** 特殊字段需要特殊的方法追加 **/
	public static String specialFieldAddition(JavaAttributeVO attriVO, String formName, String poName,
			String daoImplName) {
		StringBuilder specialFieldAddition = new StringBuilder();
		/** 自己更新方法 **/
		if (FieldUtil.getHaveselfupdatefieldlist().indexOf(attriVO.getName()) >= 0) {
			specialFieldAddition.append(update(formName, poName, daoImplName, NameUtil.updateName(attriVO.getName())));
		}
		return specialFieldAddition.toString();
	}

	public static String head(TablePO tablePO, String daoImplName, String daoApiName) {
		StringBuilder methodStr = new StringBuilder();
		methodStr.append("package ")
				.append(PathUtil.createPackagePath(tablePO.getTable_name(), FileNameEnumType.SERVICE_NAME))
				.append(CommonCodeUtil.importClass())

				.append("/**\n").append("  *").append(tablePO.getTable_comment()).append("\n").append("  *@author ")
				.append(System.getProperties().getProperty("user.name")).append("\n").append("  *@version 1.0.0 ")
				.append(DateUtil.dateFormat(new Date(), DateUtil.DATE_FORMAT)).append(" \n").append("  */\n")
				.append(" @Service(\"")
				.append(NameUtil.createSpringServiceName(
						NameUtil.createFileName(tablePO.getTable_name(), FileNameEnumType.SERVICE_NAME)))
				.append("\") \n").append("public class ")
				.append(NameUtil.createFileName(tablePO.getTable_name(), FileNameEnumType.SERVICE_NAME))
				.append("  implements ")
				.append(NameUtil.createFileName(tablePO.getTable_name(), FileNameEnumType.SERVICE_API_NAME))
				.append("{ \n").append("		/*** 日志*/ \n").append(CommonCodeUtil.logStatement())
				.append("		@Resource\n").append("		private ").append(daoApiName).append(" ")
				.append(daoImplName).append(";\n\n").append(CommonCodeUtil.redisStatement());
		return methodStr.toString();
	}

	/** 修改数据状态 **/
	public static String editStatus(String poName, String daoImplName) {
		StringBuilder methodStr = new StringBuilder();
		// 更改数据状态
		methodStr.append(CommonCodeUtil.methodRemark("10 根据ids 更改数据状态 "))
				.append(CommonCodeUtil.implMethodResult("?", null, Constants.SERVICE_METHOD_EDIT_STATUS,
						" Integer state,Integer id "))
				.append(CommonCodeUtil.resultStatement("?", null))
				.append("   	 	log.debug(\"更新数据状态信息：state={},id={}\",state,id);\n")
				.append(CommonCodeUtil.tryBegin()).append(CommonCodeUtil.poNew(poName))
				.append("  					 			po.setId( id ); \n")
				.append("   							//	po.setState( state ); \n")
				.append("  // po.setStatus(state); \n ")
				.append(CommonCodeUtil.daoMethodCall(daoImplName, Constants.DAO_METHOD_EDIT_STATUS))
				.append(CommonCodeUtil.serviceCommonEx("修改数据状态"));
		return methodStr.toString();
	}

	/** 集合 **/
	public static String list(String formName,String voName, String poName, String daoImplName) {
		StringBuilder methodStr = new StringBuilder();
		methodStr.append(CommonCodeUtil.methodRemark("9 条件获取数据集合 "))
				.append(CommonCodeUtil.implMethodResult("list", voName, Constants.SERVICE_METHOD_QUERY_LIST,
						formName + " paraForm "))
				.append(CommonCodeUtil.resultStatement("list", voName)).append(CommonCodeUtil.tryBegin())
				.append("				").append(poName).append(" po = paraForm.convertToPO();\n")
				.append(CommonCodeUtil.listPO(poName))
				.append(CommonCodeUtil.daoMethodCall(daoImplName, Constants.DAO_METHOD_QUERY_LIST))
				.append("				resultVO.setData(this.createVOList(poList)); \n ")
				.append("               resultVO.setRecordsTotal(Long.valueOf(poList.size())); \n ")
				.append(CommonCodeUtil.serviceCommonEx("获取数据集合"));
		return methodStr.toString();
	}

	/** 批量修改状态 **/
	public static String editStatusBatch(String poName, String daoImplName) {
		StringBuilder methodStr = new StringBuilder();
		methodStr.append(CommonCodeUtil.methodRemark("6 根据ids 更改数据状态"))
				.append(CommonCodeUtil.implMethodResult("?", null, Constants.SERVICE_METHOD_EDIT_STATUS_BATCH,
						" Integer state,Integer[] ids "))
				.append(CommonCodeUtil.resultStatement("?", null))
				.append(" String idStr = NumberUtil.arrayToStr(ids);\n")
				.append(" log.debug(\"更新数据状态信息：state：{},ids={}\" ,state,idStr);\n").append(CommonCodeUtil.tryBegin())
				.append(CommonCodeUtil.poNew(poName)).append(" //po_.setIds_( ids ); \n")
				.append(" po_.setState( state ); \n").append(" this.").append(daoImplName).append(".")
				.append(Constants.DAO_METHOD_EDIT_STATUS_BATCH).append("(po );\n")
				.append(CommonCodeUtil.serviceCommonEx("批量更改数据状态"));
		return methodStr.toString();
	}

	/** 分页 **/
	public static String page(String formName,String voName, String poName, String daoImplName) {
		StringBuilder methodStr = new StringBuilder();
		methodStr.append(CommonCodeUtil.methodRemark("5查询分页"))
				.append(CommonCodeUtil.implMethodResult("list", voName, Constants.SERVICE_METHOD_QUERY_PAGE,
						formName + " paraForm "))
				.append(CommonCodeUtil.resultStatement("list", voName))
				.append(" if (null == paraForm.getPageNumber() || null == paraForm.getPageSize()) { \n ")
				.append(" log.info(\"参数为空paraForm={}\", paraForm); \n ")
				.append(" return new ResultVO<>(\"e.parameter.is.null\"); \n ")
				.append(" } \n")
				.append(CommonCodeUtil.tryBegin())
				.append(" 				//生成po \n").append("				").append(poName)
				.append(" po = paraForm.convertToPO();\n").append(" 				//查询数量  \n")
				.append(" 				Long totalNum = ")
				.append(CommonCodeUtil.daoMethodCall(daoImplName, Constants.DAO_METHOD_QUERY_COUNT_NUM))
				.append(" Page<?> page = new Page<>(paraForm.getPageNumber(), paraForm.getPageSize(), totalNum.intValue()); \n ")
				.append(" po.setPageNumber(page.getStartRow()); \n ").append(" po.setPageSize(page.getPageSize()); \n")
				.append(" 				//查询你全部数据  \n").append(" 				List<").append(poName)
				.append("> poList = this.").append(daoImplName).append(".").append(Constants.DAO_METHOD_QUERY_PAGE)
				.append("( po );\n").append("                resultVO.setData(this.createVOList(poList)); \n  ")
				.append("               resultVO.setRecordsTotal(totalNum);  \n ")
				.append(CommonCodeUtil.serviceCommonEx("查询数据异常"));
		return methodStr.toString();
	}

	/** 根据id查询 **/
	public static String queryById(String voName, String poName, String daoImplName) {
		StringBuilder methodStr = new StringBuilder();
		// 根据id查询
		methodStr.append(CommonCodeUtil.methodRemark("4根据id查询数据"))
				.append(CommonCodeUtil.implMethodResult("vo", voName, Constants.DAO_METHOD_QUERY_BY_ID, " Integer id "))
				.append(CommonCodeUtil.resultStatement("vo", voName)).append(CommonCodeUtil.poNew(poName))
				.append(" po.setId(id); \n ").append(CommonCodeUtil.tryBegin()).append(poName).append(" resultPO = ")
				.append(CommonCodeUtil.daoMethodCall(daoImplName, Constants.DAO_METHOD_QUERY_BY_ID))
				.append(" 	resultVO.setData(createVO(resultPO));\n").append(CommonCodeUtil.serviceCommonEx("根据id查询数据"));
		return methodStr.toString();
	}

	/** 新增 **/
	public static String add(String formName, String poName, String daoImplName) {
		StringBuilder methodStr = new StringBuilder();
		methodStr.append(CommonCodeUtil.methodRemark("3 新增数据信息 "))
				.append(CommonCodeUtil.implMethodResult("form", formName, Constants.DAO_METHOD_INSERT, formName + " paraForm "))
				.append(" ").append(Constants.RESINFO_VO).append(" <").append(formName)
				.append("> resultVO = addValidate(paraForm);\n")
				.append("        if (resultVO.isSuccess()) { \n")
				.append("          	log.debug(\"数据重复直接返回 msg={}\",resultVO.getMsg()); \n")
				.append("        //返回ture 表示数据重复，这里返回调用操作需要返回false   \n")
				.append("        resultVO.setSuccess(false); \n ")
				.append("          	return resultVO;\n").append("         } // end if \n ").append("			")
				.append(poName).append(" po =paraForm.convertToPO() ;\n").append(CommonCodeUtil.tryBegin())
				.append(" // po.setId(KeyAutoCreateUtil.makePrimaryLong(PrimarykeyEnum.SX_T_E_BROWSE_RECORDS,cache)); \n")
				.append("                //Long id = Long.valueOf(SquenceUtil.makePrimarykey(PrimarykeyClass.SX_SHOPPING_CATEGORY,\"\", cache) );\n")
				.append("                //po.setId(id); \n")
				.append("  // po.setId(KeyAutoCreateUtil.keyCreate()); \n ")
				.append(CommonCodeUtil.daoMethodCall(daoImplName, Constants.DAO_METHOD_INSERT))
				.append("paraForm.setId(po.getId()); \n ")
				.append(" resultVO.setData(paraForm); \n ")
				.append(CommonCodeUtil.serviceCommonEx("新增数据"));
		return methodStr.toString();
	}

	/** 批量新增 **/
	public static String addBatch(String formName, String poName, String daoImplName) {
		StringBuilder methodStr = new StringBuilder();
		methodStr.append(CommonCodeUtil.methodRemark("3 批量新增数据信息"))
				.append(CommonCodeUtil.implMethodResult("?", formName, Constants.DAO_METHOD_INSERT_BATCH,
						" List<" + formName + "> formList "))
				.append(CommonCodeUtil.resultStatement("?", null))
				.append("       if(null==formList || formList.isEmpty() ){ \n")
				.append("  resultVO.setMsg(\"参数为空\"); \n ").append("          	return resultVO;\n")
				.append("         } // end if \n ").append(" List<").append(poName)
				.append("> poList = createPOList(formList);\n").append(CommonCodeUtil.tryBegin())
				.append(daoImplName).append(".").append( Constants.DAO_METHOD_INSERT_BATCH).append(" (poList); \n")
				.append(CommonCodeUtil.serviceCommonEx("批量新增数据"));
		return methodStr.toString();
	}

	/** 删除 **/
	public static String deleteById(String poName, String daoImplName) {
		StringBuilder methodStr = new StringBuilder();
		methodStr.append(CommonCodeUtil.methodRemark("1根据id删除数据"))
				.append(CommonCodeUtil.implMethodResult("?", null, Constants.DAO_METHOD_DELETE_BY_ID, " Integer id "))
				.append("    		log.debug(\"根据id删除数据id={}\",id); \n")
				.append(CommonCodeUtil.resultStatement("?", null)).append(CommonCodeUtil.poNew(poName))
				.append("  				po.setId( id ); \n").append(CommonCodeUtil.tryBegin())
				.append("				log.debug(\"开始删除数据po={}\",po); \n")
				.append(CommonCodeUtil.daoMethodCall(daoImplName, Constants.DAO_METHOD_DELETE_BY_ID))
				.append(CommonCodeUtil.serviceCommonEx("删除数据"));
		return methodStr.toString();
	}

	/** 修改 **/
	public static String update(String formName, String poName, String daoImplName) {
		return update(formName, poName, daoImplName, Constants.DAO_METHOD_UPDATE);
	}

	/** 修改 **/
	public static String update(String formName, String poName, String daoImplName, String methodName) {
		StringBuilder methodStr = new StringBuilder();
		methodStr.append(CommonCodeUtil.methodRemark("2更新数据信息"))
				.append(CommonCodeUtil.implMethodResult("?", formName, methodName, formName + " paraForm"))
				.append(CommonCodeUtil.resultStatement("?", null)).append(poName).append(" po = paraForm.convertToPO() ;\n")
				.append(CommonCodeUtil.tryBegin()).append(CommonCodeUtil.daoMethodCall(daoImplName, methodName))
				.append(CommonCodeUtil.serviceCommonEx("修改数据"));
		return methodStr.toString();
	}

	/** createVO **/
	public static String createVO(String voName, String poName) {
		StringBuilder str = new StringBuilder();
		// createVO方法
		str.append("	/**  po to vo **/ \n").append("	private ").append(voName).append(" createVO(").append(poName)
				.append(" po ){ \n").append("            if( null == po){  \n")
				.append("                return null; \n  ").append("             } \n").append("		return new ")
				.append(voName).append(" (po); \n } //end createVO  \n \n \n ");
		return str.toString();
	}

	/** voList 2 poList **/
	public static String createPOList(String formName, String poName) {
		StringBuilder str = new StringBuilder();
		str.append("	/**  voList 2 poList   **/	\n").append("	private List<").append(poName)
				.append("> createPOList( List<").append(formName).append("> voList ){ \n")
				.append("		if( null == voList || voList.isEmpty()){ \n ")
				.append("			return new ArrayList<>();\n").append("		} \n").append("		//返回的集合\n")
				.append("		List<").append(poName).append("> poList = new ArrayList<>( voList.size() ); \n")
				.append("		//批量数据复制 \n").append("		for(").append(formName).append(" paraForm : voList){\n")
				.append(poName).append(" po =paraForm.convertToPO(); \n ")
				.append(" //po.setId(KeyAutoCreateUtil.keyCreate()); \n ")
				.append(" // po.setId(KeyAutoCreateUtil.makePrimaryLong(PrimarykeyEnum.SX_T_E_BROWSE_RECORDS,cache)); \n")
				.append(" poList.add(po); \n ")
				.append("		// poList.add(vo.convertToPO()); \n ").append("		}\n")
				.append("		return poList; \n } \n");
		return str.toString();
	}
	// 类型转换

	/** poList 2 voList **/
	public static String createVOList(String voName, String poName) {
		StringBuilder str = new StringBuilder();
		str.append("	/**  poList 2 voList 类  **/	\n").append("	private List<").append(voName)
				.append("> createVOList( List<").append(poName).append("> poList ){ \n")
				.append("		if( null == poList || poList.isEmpty()){ \n ")
				.append("			return new ArrayList<>();\n").append("		} \n").append("		//返回的集合\n")
				.append("		List<").append(voName).append("> voList = new ArrayList<>( poList.size() ); \n")
				.append("		//批量数据复制 \n").append("		for(").append(poName).append(" po : poList){\n")
				.append("			//类型转换 \n").append("			voList.add( this.createVO(po) );\n")
				.append("		} \n ").append("		return voList; \n } \n ");
		return str.toString();
	}

	/** 添加时唯一性的验证 **/
	public static String addValidate(String formName, String poName, String daoImplName) {
		StringBuilder str = new StringBuilder();
		// 添加时唯一性的验证
		str.append("/** 添加时唯一性的验证**/ \n").append(" private ").append(Constants.RESINFO_VO).append("<").append(formName)
				.append("> addValidate(").append(formName).append(" paraForm){ \n").append(" 	log.debug(\"").append(formName)
				.append("添加时唯一性验证paraForm={}\",paraForm); \n").append(Constants.RESINFO_VO).append(" <").append(formName)
				.append("> uniqueValidate = new ").append(Constants.RESINFO_VO).append("<>(); \n")
				.append(CommonCodeUtil.poNew(poName))
				// .append(" ").append(poName).append(" po = new ").append(poName).append("();\n
				// \n \n")
				.append(" 	log.debug(\"检查重复数据po={}\",po);\n").append(" 	List<").append(poName)
				.append("> poList =  this.").append(daoImplName).append(".")
				.append(Constants.DAO_METHOD_QUERY_LIST_VALIDATE).append("(po);\n")
				.append(" 	if( !poList.isEmpty()){ \n")
				.append(" 		log.debug(\"数据重复size={},paraForm={}\",poList.size(),paraForm); \n")
				.append("    paraForm.setId(poList.get(0).getId()); \n ").append("     uniqueValidate.setData(paraForm);  \n ")
				.append(" 		uniqueValidate.setMsg(\"重复\");\n").append("         return uniqueValidate; \n ")
				.append("    } // end if \n \n").append("   uniqueValidate.setSuccess(false);\n ")
				.append("    return uniqueValidate;\n").append(" } \n");
		return str.toString();
	}

	/** 编辑时唯一性的验证 **/
	public static String updateValidate(String formName, String poName, String daoImplName) {
		StringBuilder str = new StringBuilder();
		str.append("/** 编辑时唯一性的验证**/ \n").append(" private ").append(Constants.RESINFO_VO).append("<").append(formName)
				.append("> updateValidate(").append(formName).append(" vo){ \n ").append("log.debug(\"").append(formName)
				.append("添加时唯一性验证vo={}\",vo); \n ").append(Constants.RESINFO_VO).append("<").append(formName)
				.append("> uniqueValidate = new ").append(Constants.RESINFO_VO).append("<>(); \n")
				// .append(" ").append(poName).append(" queryPO = new
				// ").append(poName).append("();\n \n \n")
				.append(CommonCodeUtil.poNew(poName)).append(" 	log.debug(\"检查重复数据queryPO={}\",po);\n")
				.append(" 	List<").append(poName).append("> poList =  this.").append(daoImplName).append(".")
				.append(Constants.DAO_METHOD_QUERY_LIST_VALIDATE).append("(po);\n")
				.append(" 	if( !poList.isEmpty()){ \n").append(" for (").append(poName)
				.append(" poTemp : poList) {	\n").append(" if (!poTemp.getId().equals(vo.getId())) { \n ")
				.append(" log.info(\"重复vo={}\",vo); \n ").append(" 		uniqueValidate.setMsg(\"重复\");\n")
				.append("         return uniqueValidate; \n ").append(" }// end if").append(" \n ")
				.append("    } // end for ").append(" \n ").append("} // end if").append(" \n ")
				.append("    uniqueValidate.setSuccess(false); \n ")
				.append("    return uniqueValidate;\n").append(" } \n");

		return str.toString();
	}

}
